#!/usr/bin/python
# -*- coding: utf-8 -*-
# AUTHOR:   yemd
# FILENAME: py_common_log.py
# DESCRIBE: 日志打印封装库
# CREATED:  2014-01-15 14:29
# MODIFIED: 2014-02-11 13:41

import sys,os
import time
import string
import inspect
from dm_py_util import *
import common_log


LEVEL_TYPE_LIST = [common_log.LOGDEBUG,
				   common_log.LOGINFO,
				   common_log.LOGWARN,
				   common_log.LOGERROR]

INTERNAL_TYPE_LIST = [common_log.LOG_INTERVAL_HOUR,
					  common_log.LOG_INTERVAL_DAY,
					  common_log.LOG_INTERVAL_MONTH,
					  common_log.LOG_INTERVAL_YEAR]

LOG_TYPE_DICT = {common_log.LOG_TYPE_PROGRAM:"program",
				 common_log.LOG_TYPE_ERROR:"error",
				 common_log.LOG_TYPE_BUSINESS:"business"} 


"""
common_logger不初始化，直接输出print内容，不打印到文件
"""
py_common_logger=None

def INIT_LOG(config):
	if not config:
		raise DM_InputError('config is None')
	try:
		cfgparser = PYC_ConfigParser(config)
		Path = cfgparser.get_config("py_common_logger","log_path")
		Pre = cfgparser.get_config("py_common_logger","log_pre")
		Level = int(cfgparser.get_config("py_common_logger","log_level"))
		Interval = int(cfgparser.get_config("py_common_logger","log_interval"))
		Key = cfgparser.get_config("py_common_logger","log_key")
		#声明一个全局日志的变量
		global py_common_logger  
		py_common_logger = PY_Common_Log()  
		if py_common_logger.init(Path,Pre,Level,Interval,Key)<0:
			raise DM_InputError("py_common_logger module init error")
		#py_common_logger.print_log()
	except Exception,e:
		raise DM_InputError("init error",str(e))

def SET_LOG_KEY(log_key):
	if py_common_logger:
		py_common_logger.set_log_key(log_key)

def DEBUG_LOG(*debug_log_args):
	if py_common_logger is None:
		print "|".join(["DEBUG",":".join((str(e) for e in debug_log_args))])
	else:
		py_common_logger.debug(*debug_log_args)

def INFO_LOG(*info_log_args):
	if py_common_logger is None:
		print "|".join(["INFO",":".join((str(e) for e in info_log_args))])
	else:
		py_common_logger.info(*info_log_args)

def WARN_LOG(*warn_log_args):
	if py_common_logger is None:
		print "|".join(["WARN",":".join((str(e) for e in warn_log_args))])
	else:
		py_common_logger.warn(*warn_log_args)

def ERROR_LOG(*error_log_args):
	if py_common_logger is None:
		print "|".join(["ERROR",":".join((str(e) for e in error_log_args))])
	else:
		py_common_logger.error(*error_log_args)

def BUSINESS_LOG(*business_log_args):
	if py_common_logger is None:
		print "|".join(["BUSINESS",":".join((str(e) for e in business_log_args))])
	else:
		py_common_logger.business(*business_log_args)




"""
日志类
"""
class PY_Common_Log():
	def __init__(self,Path='./',Pre='',\
				 Level=common_log.LOGDEBUG,\
				 Interval=common_log.LOG_INTERVAL_YEAR,\
				 Key="mylog"):
		self._log_path = Path 
		self._log_pre = Pre
		self._log_level = Level             #默认DEBUG级别,即所有都打印
		self._log_interval = Interval
		self._log_key = Key
		self._logger = None                 #日志实例
		self._record_log_key = "common"     #用于记录某条日志的名称,便于日志分析 
		self._cn_ = self.__class__.__name__ #classname,for log debug
	
	def print_log(self):
		print "start!!!!!!!!!!!!!!!!!!!!!!!!"
		print "path=",self._log_path
		print "pre=",self._log_pre
		print "level=",self._log_level
		print "interval=",self._log_interval
		print "key=",self._log_key
		print "record_key=",self._record_log_key


	def init(self,Path,Pre='',\
			 Level=common_log.LOGDEBUG,\
			 Interval=common_log.LOG_INTERVAL_YEAR,\
			 Key='mylog'):
		_fn_ = inspect.currentframe().f_code.co_name
		#check args#
		if not self._log_path:
			print "Path is empty,invalid!!!"
			return -1
		if self._log_level not in LEVEL_TYPE_LIST:
			print 'Level invalid!!!(example:0/1/2/3)'
			return -1
		if self._log_interval not in INTERNAL_TYPE_LIST:
			print 'Interval invalid!!!(example:0/1/2/3)'
			return -1
		if not self._log_key:
			print "Key is empty,invalid!!!"
			return -1
		#初始化成员变量
		self.__init__(Path,Pre,Level,Interval,Key)
		#开始创建logger实例#
		error_path = self._get_log_name(common_log.LOG_TYPE_ERROR)
		progrom_path = self._get_log_name(common_log.LOG_TYPE_PROGRAM)
		business_path = self._get_log_name(common_log.LOG_TYPE_BUSINESS)
		#print error_path
		#print progrom_path
		#print business_path
		retnum = common_log.InitLog(error_path,\
									progrom_path,\
									business_path,\
									self._log_level,\
									self._log_interval,\
									self._log_key)
		if retnum < 0:
			print "common_log.InitLog error"
			return -1
		#初始化成功，获取logger句柄
		self._logger = common_log.GetLogger()
		if not self._logger:
			print "common_log.GetLogger is None error"
			return -1
		return 0


	#拼装日志格式#
	def _get_log_name(self,log_type):
		if self._log_pre:
			path_pre = "/".join([self._log_path,self._log_pre])
			return "_".join([path_pre,LOG_TYPE_DICT[log_type]])
		else:
			return "/".join([self._log_path,LOG_TYPE_DICT[log_type]])

	#设置日志记录标识#
	def set_log_key(self,record_key):
		self._record_log_key = record_key

	#调试日志文件输出
	def debug(self,*format_args):
		databuf = "|".join([self._record_log_key,":".join((str(e) for e in format_args))])
		self._logger.ProgramLog(common_log.LOGDEBUG,"%s"%(databuf))
	
	def info(self,*format_args):
		databuf = "|".join([self._record_log_key,":".join((str(e) for e in format_args))])
		self._logger.ProgramLog(common_log.LOGINFO,"%s"%(databuf))

	def warn(self,*format_args):
		databuf = "|".join([self._record_log_key,":".join((str(e) for e in format_args))])
		self._logger.ProgramLog(common_log.LOGWARN,"%s"%(databuf))

	#错误日志文件输出,特别地错误同时也会打到调试日志中
	def error(self,*format_args):
		databuf = "|".join([self._record_log_key,":".join((str(e) for e in format_args))])
		self._logger.ProgramLog(common_log.LOGERROR,"%s"%(databuf))

	#业务日志文件输出
	def business(self,*format_args):
		databuf = "|".join((str(e) for e in format_args))
		self._logger.BusinessLog("%s"%(databuf))

	#自动释放logger
	#def __del__(self):
	#	if self._logger:
	#		common_log.ReleaseLog()


if __name__ == "__main__":
	_fn_ = "main"
	log_config = '../log.config'	
	mode = 0
	if len(sys.argv) == 2:
		mode = int(sys.argv[1])
	#控制台直接输出测试#
	if mode == 1:
		DEBUG_LOG("output",_fn_,"data","real",1111)
		INFO_LOG("output",_fn_,"info","test",22222222)
		WARN_LOG("output",_fn_,"warning",4444444444)
		ERROR_LOG("output",_fn_,"error!!!!!!!",77777777777)
		BUSINESS_LOG("output","192.168.10.124","interface","request",10101010)
	#文件输出测试#
	else:
		try:
			INIT_LOG(log_config)
		except Exception,e:
			print 'error:%s'%(str(e))
			exit(-1)
		times = 0
		while True:
			times = times + 1
			SET_LOG_KEY("TEST")
			DEBUG_LOG("interface",_fn_,"data","real",times)
			INFO_LOG("interface",_fn_,"info","test",times)
			WARN_LOG(_fn_,"warning",times)
			ERROR_LOG(_fn_,"error!!!!!!!",times)
			BUSINESS_LOG("192.168.10.124","interface","request",times)
			time.sleep(2)
			if times > 2:
				print "finish loop!!!!!!!!!!!!!!!!!!!!"
				break
	exit(0)
